package com.huan.vertxle.initialization;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Slf4JLoggerFactory;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.redis.client.Redis;
import io.vertx.redis.client.RedisConnection;
import io.vertx.redis.client.RedisOptions;

/**
 * @author huan
 */
public class RedisInit {
  private final InternalLogger logger = Slf4JLoggerFactory.getInstance(this.getClass());

  public static RedisConnection client;

  public void init() {
    createRedisClient().onSuccess(redisConnection -> {
      // 连接到redis！
      client = redisConnection;
      logger.info("redis 初始化成功");
    }).onFailure(throwable -> {
      logger.error("redis初始化失败:{}", throwable.getMessage());
      Vertx.currentContext().owner().close();
    });
  }

  /**
   * 将创建一个redis客户端并在存在以下情况时设置一个重新连接处理程序 连接中的异常。
   */
  private Future<RedisConnection> createRedisClient() {
    Promise<RedisConnection> promise = Promise.promise();
    RedisOptions options = new RedisOptions();
    options.addConnectionString(StartParamsInit.init.getRedis().getConnection());
    Redis.createClient(Vertx.currentContext().owner(), options).connect().onSuccess(redisConnection -> {
      redisConnection.exceptionHandler(e -> {
        // 如果有不可恢复的错误
        promise.fail(e.getCause());
      });
      // 允许进一步处理
      promise.complete(redisConnection);
    }).onFailure(promise::fail);
    return promise.future();
  }
}
